package com.hq.ims.data.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hq.ims.data.config.verification.VdAdd;
import com.hq.ims.data.config.verification.VdEdit;
import com.hq.ims.data.dao.BusForewarningSetMapper;
import com.hq.ims.data.entity.BusForewarningSet;
import com.hq.ims.data.entity.SmsTemplate;
import com.hq.ims.data.entityenum.EnumBusKey;
import com.hq.ims.data.entityenum.EnumFeedbackPhase;
import com.hq.ims.data.entityenum.EnumUserType;
import com.hq.ims.data.vo.BusForewarningSetMapstruct;
import com.hq.ims.data.vo.SmsTemplateMapstruct;
import com.hq.mybatis.base.BaseService;
import com.hq.mybatis.base.page.RequestPage;
import com.hq.utils.util.*;
import com.hq.web.utils.SpringBootValidateUtils;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 蒋柏平
 * @detail 预警设置 服务实现类
 * @since 20241011
 */
@Service
public class BaseBusForewarningSetService extends BaseService<BusForewarningSetMapper, BusForewarningSet> {

    @Resource
    private BaseSmsTemplateService baseSmsTemplateService;

    /**
     * 分页
     */
    public List<BusForewarningSetMapstruct.BusForewarningSetVo> getByPage(
            RequestPage page,
            BusForewarningSetMapstruct.PageSearchVo searchVo
    ) {

        //验证
        LambdaQueryChainWrapper<BusForewarningSet> lq = this.lambdaQuery();
        //排序
        lq.orderByDesc(BusForewarningSet::getCreateDateTime);
        //查询条件
        if (StringUtils.isNotEmpty(searchVo.getBusKeyTypeName())) {
            List<EnumUserType> filterList = Arrays.stream(EnumUserType.values()).filter(d -> d.getTypeName().contains(searchVo.getBusKeyTypeName())).collect(Collectors.toList());
            if (ListUtils.isNotExistsEle(filterList)) {
                lq.eq(BusForewarningSet::getBusForewarningSetId, StringUtils.EMPTY);
            } else {
                lq.in(BusForewarningSet::getBusKeyType, filterList);
            }
        }

        //执行分页
        lq.page(page);

        List<BusForewarningSet> dataList = page.getRecords();
        List<BusForewarningSetMapstruct.BusForewarningSetVo> voList = BusForewarningSetMapstruct.INSTANCE.toBusForewarningSetVoList(dataList);
        baseSmsTemplateService.fillListOneToOne(voList, d -> d.getSmsCode(), (k, v) -> {
            if (v != null) {
                k.setSmsContext(v.getSmsContext());
            }
        });
        return voList;
    }

    /**
     * 添加
     */
    @Transactional(rollbackFor = Exception.class)
    public BusForewarningSet addData(BusForewarningSetMapstruct.SaveVo vo) {
        //验证
        SpringBootValidateUtils.validate(vo, VdAdd.class);
        boolean existsBusKey = this.isExistsBusKeyType(vo.getBusKeyType());
        BooleanUtils.isTrueThrow(existsBusKey, "业务key已存在");
        //账值新的对象
        BusForewarningSet entity = new BusForewarningSet();
        entity.setTimeHour(vo.getTimeHour());
        entity.setBusKeyType(vo.getBusKeyType());
        entity.setSmsCode(vo.getSmsCode());

        entity.insert();
        return entity;
    }

    /**
     * 业务key是否存在
     */
    public boolean isExistsBusKeyType(
            @NonNull EnumBusKey busKeyType
    ) {
        return this.lambdaQuery().eq(BusForewarningSet::getBusKeyType, busKeyType)
                .count() > 0;
    }

    /**
     * 编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public BusForewarningSet editData(BusForewarningSetMapstruct.SaveVo vo) {
        //验证
        SpringBootValidateUtils.validate(vo, VdEdit.class);

        //账值新的对象
        BusForewarningSet entity = this.getById(vo.getBusForewarningSetId());
        ObjectUtils.isNullThrow(entity, "数据不存在");

        entity.setTimeHour(vo.getTimeHour());
        entity.setSmsCode(vo.getSmsCode());

        entity.updateById();
        return entity;
    }


    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void delData(String busForewarningSetId) {
        BusForewarningSet data = this.getById(busForewarningSetId);
        if (data == null) {
            return;
        }
        data.deleteById();
    }

    /**
     * 获取详情
     */
    public BusForewarningSetMapstruct.BusForewarningSetVo getDetailVo(String busForewarningSetId) {
        BusForewarningSet busForewarningSet = this.getById(busForewarningSetId);
        BusForewarningSetMapstruct.BusForewarningSetVo vo = BusForewarningSetMapstruct.INSTANCE.toBusForewarningSetVo(busForewarningSet);
        if (StringUtils.isNotEmpty(vo.getSmsCode())) {
            SmsTemplateMapstruct.SmsTemplateVo detailVo = baseSmsTemplateService.getDetailVo(vo.getSmsCode());
            vo.setSmsContext(detailVo.getSmsContext());
        }
        return vo;
    }

    /**
     * 清除已绑定的sms
     *
     * @param smsCode 清除已绑定的短信
     */
    @Transactional(rollbackFor = Exception.class)
    public void clearBindSms(String smsCode) {
        this.lambdaUpdate()
                .eq(BusForewarningSet::getSmsCode, smsCode)
                .set(BusForewarningSet::getSmsCode, StringUtils.EMPTY)
                .update();
    }

    /**
     * 清除已绑定的sms
     */
    @Transactional(rollbackFor = Exception.class)
    public void clearBindSms() {
        List<SmsTemplate> smsTemplateList = baseSmsTemplateService.lambdaQuery().select(SmsTemplate::getSmsCode).list();
        if (ListUtils.isNotExistsEle(smsTemplateList)) {
            return;
        }
        List<String> smsCodeList = smsTemplateList.stream().map(SmsTemplate::getSmsCode).collect(Collectors.toList());
        this.lambdaUpdate()
                .notIn(BusForewarningSet::getSmsCode, smsCodeList)
                .set(BusForewarningSet::getSmsCode, StringUtils.EMPTY)
                .update();
    }

    /**
     * 根据业务key获取预警配置
     *
     * @param busKey 反馈阶段
     */
    public BusForewarningSetMapstruct.BusForewarningSetVo getByEnumBusKey(
            @NonNull EnumBusKey busKey
    ) {
        List<BusForewarningSet> list = this.lambdaQuery().eq(BusForewarningSet::getBusKeyType, busKey).list();
        if (ListUtils.isNotExistsEle(list)) {
            return null;
        }
        BusForewarningSet busForewarningSet = list.get(0);
        BusForewarningSetMapstruct.BusForewarningSetVo vo = BusForewarningSetMapstruct.INSTANCE.toBusForewarningSetVo(busForewarningSet);
        return vo;
    }

    /**
     * 根据经营信息反馈阶段获取配置
     *
     * @param feedbackPhase 反馈阶段
     */
    public BusForewarningSetMapstruct.BusForewarningSetVo getByEnumFeedbackPhase(EnumFeedbackPhase feedbackPhase) {
        EnumBusKey busKey = EnumUtils.getByName(EnumBusKey.class, feedbackPhase.name());
        if (busKey == null) {
            return null;
        }
        BusForewarningSetMapstruct.BusForewarningSetVo vo = this.getByEnumBusKey(busKey);
        return vo;
    }

    /**
     * 根据经营信息反馈阶段获取配置
     *
     * @param feedbackPhase 反馈阶段
     */
    public int getHourByEnumFeedbackPhase(EnumFeedbackPhase feedbackPhase) {
        BusForewarningSetMapstruct.BusForewarningSetVo vo = this.getByEnumFeedbackPhase(feedbackPhase);
        if (vo == null) {
            return 0;
        }
        return vo.getTimeHour();
    }
}